<template>
  <div class="publish-position-container">
    <div class="card-container">
      <div class="close-btn" @click="goBack">×</div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="publish-position-form"
      >
        <h3 class="form-title">{{ isEditMode ? "编辑岗位" : "发布岗位" }}</h3>

        <el-form-item label="职位类型" prop="positionType">
          <el-select
            v-model="selectedIndustryId"
            placeholder="请选择行业"
            style="width: 100%"
            @change="handleIndustryChange"
          >
            <el-option
              v-for="industry in positionTypeOptions"
              :key="industry.id"
              :label="industry.name"
              :value="industry.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="职位类别" prop="categoryId">
          <el-select
            v-model="selectedCategoryId"
            placeholder="请先选择行业"
            style="width: 100%"
            :disabled="!positionCategories.length"
            @change="handleCategoryChange"
          >
            <el-option
              v-for="category in positionCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="职位名称" prop="positionName">
          <el-select
            v-model="ruleForm.positionName"
            placeholder="请先选择行业和类别"
            style="width: 100%"
            :disabled="!positionNames.length"
          >
            <el-option
              v-for="name in positionNames"
              :key="name.id"
              :label="name.name"
              :value="name.name"
            />
          </el-select>
        </el-form-item>

        <!-- 其他表单项保持不变 -->
        <el-form-item label="学历要求" prop="education">
          <el-select
            v-model="ruleForm.education"
            placeholder="请选择学历要求"
            style="width: 100%"
          >
            <el-option label="大专" value="COLLEGE"></el-option>
            <el-option label="本科" value="UNDERGRADUATE"></el-option>
            <el-option label="硕士" value="MASTER"></el-option>
            <el-option label="博士" value="DOCTOR"></el-option>
            <el-option label="其他" value="OTHER"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="薪资范围" prop="salaryRange">
          <el-row :gutter="10" class="salary-row">
            <el-col :span="10">
              <el-input
                v-model.number="ruleForm.lowestSalaryMonth"
                placeholder="最低月薪"
                style="width: 100%"
              >
                <template #append>元/月</template>
              </el-input>
            </el-col>
            <el-col :span="2" class="salary-divider">——</el-col>
            <el-col :span="10">
              <el-input
                v-model.number="ruleForm.highestSalaryMonth"
                placeholder="最高月薪"
                style="width: 100%"
              >
                <template #append>元/月</template>
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="职位详情" prop="positionDetail">
          <el-input
            type="textarea"
            v-model="ruleForm.positionDetail"
            :rows="4"
            placeholder="请详细描述岗位内容、职责和福利"
          ></el-input>
        </el-form-item>

        <el-form-item label="职位要求" prop="positionRequire">
          <el-input
            type="textarea"
            v-model="ruleForm.positionRequire"
            :rows="3"
            placeholder="请填写岗位所需技能、经验和其他要求"
          ></el-input>
        </el-form-item>

        <el-form-item label="截止日期" prop="endAt">
          <el-date-picker
            type="date"
            placeholder="招聘截止日期"
            v-model="ruleForm.endAt"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
            type="primary"
            @click="submitForm('ruleForm')"
            :loading="isSubmitting"
            class="submit-button"
          >
            {{ isEditMode ? "保存编辑" : "发布岗位" }}
          </el-button>
          <el-button @click="resetForm('ruleForm')" class="reset-button">
            重置表单
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getUserPositionById,
  getUserPublishPositionByCode,
  publishPosition,
  resubmitPublishPosition,
  updateUserPosition,
  getAllPositionIndustries,
  getPositionCategoriesByIndustryId,
  getPositionNamesByCategoryId,
} from "@/api/recuriter/position";

import { getPositionAllMessageByIndustryAndName } from "@/api/recuriter/register";

export default {
  props: {
    id: {
      type: String,
      required: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: "pending",
    },
    scene: {
      type: String,
      default: "initial",
    },
  },
  data() {
    return {
      isEditMode: false,
      currentId: null,
      ruleForm: {
        positionType: "", // 职位类型（行业名称）
        positionName: "", // 职位名称
        education: "",
        lowestSalaryMonth: null,
        highestSalaryMonth: null,
        positionDetail: "",
        positionRequire: "",
        endAt: "",
      },
      // 三级选择器数据
      positionTypeOptions: [], // 一级：行业列表
      positionCategories: [], // 二级：类别列表
      positionNames: [], // 三级：岗位名称列表
      selectedIndustryId: null, // 当前选中的行业ID
      selectedCategoryId: null, // 当前选中的类别ID（仅用于加载职位名称，不提交）
      isSubmitting: false,
      rules: {
        positionType: [
          { required: true, message: "请选择职位类型", trigger: "change" },
        ],
        positionName: [
          { required: true, message: "请选择职位名称", trigger: "change" },
        ],
        education: [
          { required: true, message: "请选择学历要求", trigger: "change" },
        ],
        lowestSalaryMonth: [
          { required: true, message: "请输入最低月薪", trigger: "blur" },
          { type: "number", message: "请输入有效数字", trigger: "blur" },
        ],
        highestSalaryMonth: [
          { required: true, message: "请输入最高月薪", trigger: "blur" },
          { type: "number", message: "请输入有效数字", trigger: "blur" },
          { validator: this.validateSalary, trigger: "blur" },
        ],
        positionDetail: [
          { required: true, message: "请填写职位详情", trigger: "blur" },
        ],
        positionRequire: [
          { required: true, message: "请填写职位要求", trigger: "blur" },
        ],
        endAt: [
          {
            type: "date",
            required: true,
            message: "请选择截止日期",
            trigger: "change",
          },
        ],
      },
    };
  },

  async created() {
    const id = this.$route.params.id;
    console.log(id);
    console.log(this.mode);
    if (id) {
      this.isEditMode = true;
      this.currentId = id;
      this.loadPositionTypes();
      this.loadEditData();
    } else {
      this.loadPositionTypes();
    }
  },

  methods: {
    async loadEditData() {
      let res;
      try {
        if (
          [
            "VERIFY_COMPANY_FAILED",
            "VERIFY_MANAGER_FAILED",
            "VERIFY_COMPANY_REVIEW",
            "VERIFY_MANAGER_REVIEW",
          ].includes(this.mode) &&
          this.scene === "code"
        ) {
          res = await getUserPublishPositionByCode(this.currentId);
        } else {
          res = await getUserPositionById(this.currentId);
        }
        this.ruleForm = {
          positionType: res.data[0].current.positionType,
          positionName: res.data[0].current.positionName,
          education: res.data[0].current.education,
          lowestSalaryMonth: res.data[0].current.lowestSalaryMonth,
          highestSalaryMonth: res.data[0].current.highestSalaryMonth,
          positionDetail: res.data[0].current.positionDetail,
          positionRequire: res.data[0].current.positionRequire,
          endAt: new Date(res.data[0].current.endAt),
        };
        this.$nextTick(async () => {
          if (!this.ruleForm.positionType || !this.ruleForm.positionName) {
            console.warn("职位类型或名称为空，无法获取三级ID");
            return;
          }

          try {
            const positionResp = await getPositionAllMessageByIndustryAndName(
              this.ruleForm.positionType,
              this.ruleForm.positionName
            );

            if (positionResp.data.code === 201 && positionResp.data.data) {
              const { industryId, categoryId, detailId } =
                positionResp.data.data;

              this.selectedIndustryId = industryId;

              if (industryId) {
                await this.handleIndustryChange(industryId);
                this.selectedCategoryId = categoryId;
                if (categoryId) {
                  await this.handleCategoryChange(categoryId);

                  this.ruleForm.positionName = res.data[0].current.positionName;
                }
              }
            } else {
              console.warn("接口未返回有效职位ID数据");
            }
          } catch (error) {
            console.error("获取职位三级ID失败：", error);
            this.$message.warning("职位信息加载不完整，手动选择选项");
          }
        });
      } catch (error) {
        console.error("错误信息", error);
        this.$message.error("数据异常");
      }
    },
    async loadPositionTypes() {
      try {
        const res = await getAllPositionIndustries();
        if (res.data.code === 201) {
          this.positionTypeOptions = res.data.data.map((item) => ({
            id: item.id,
            name: item.industryName,
          }));
        } else {
          this.$message.error("加载行业列表失败");
        }
      } catch (error) {
        console.error("行业列表加载失败：", error);
        this.$message.error("加载行业列表失败");
      }
    },

    // 行业选择变化时，加载对应的类别列表
    async handleIndustryChange(industryId) {
      this.selectedIndustryId = industryId;
      this.selectedCategoryId = null; // 重置类别选择
      this.ruleForm.positionName = ""; // 重置职位名称
      this.positionNames = []; // 清空职位名称列表

      if (!industryId) {
        this.positionCategories = [];
        return;
      }

      try {
        const res = await getPositionCategoriesByIndustryId(industryId);
        if (res.data.code === 201) {
          this.positionCategories = res.data.data.map((item) => ({
            id: item.id,
            name: item.categoryName,
          }));
          const selectedIndustry = this.positionTypeOptions.find(
            (item) => item.id === industryId
          );
          this.ruleForm.positionType = selectedIndustry?.name || "";
        } else {
          this.positionCategories = [];
          this.$message.error("加载类别列表失败");
        }
      } catch (error) {
        console.error("加载类别列表失败：", error);
        this.positionCategories = [];
        this.$message.error("加载类别列表失败");
      }
    },

    // 类别选择变化时，加载对应的职位名称列表
    async handleCategoryChange(categoryId) {
      this.selectedCategoryId = categoryId;
      this.ruleForm.positionName = ""; // 重置职位名称

      if (!categoryId) {
        this.positionNames = [];
        return;
      }

      try {
        const res = await getPositionNamesByCategoryId(categoryId);

        if (res.data.code === 201) {
          this.positionNames = res.data.data.map((item) => ({
            id: item.id || item.detailName,
            name: item.detailName,
          }));
        } else {
          this.positionNames = [];
          this.$message.error("加载职位名称列表失败");
        }
      } catch (error) {
        console.error("加载职位名称列表失败：", error);
        this.positionNames = [];
        this.$message.error("加载职位名称列表失败");
      }
    },

    validateSalary(rule, value, callback) {
      if (this.ruleForm.lowestSalaryMonth !== null && value !== null) {
        value < this.ruleForm.lowestSalaryMonth
          ? callback(new Error("最高薪资不能低于最低薪资"))
          : callback();
      } else {
        callback();
      }
    },

    // 重置表单
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
        this.selectedIndustryId = null;
        this.selectedCategoryId = null;
        this.positionCategories = [];
        this.positionNames = [];
      });
    },

    // 提交表单
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return;

        try {
          this.isSubmitting = true;
          const submitData = {
            ...this.ruleForm,
          };
          let response;
          if (
            this.isEditMode &&
            ["VERIFY_COMPANY_REVIEW", "VERIFY_MANAGER_REVIEW"].includes(
              this.mode
            )
          ) {
            submitData.code = this.currentId;

            response = await resubmitPublishPosition(submitData);
          } else if (this.isEditMode && this.mode === "NORMAL") {
            submitData.positionId = this.currentId;
            response = await updateUserPosition(submitData);
          } else {
            response = await publishPosition(submitData);
          }
          if (response.data.code === 201) {
            this.$store.commit("recruiter/SET_TOKEN", response.data.data.token);
            this.$store.commit(
              "recruiter/SET_JOBPOSTING_STATUS",
              response.data.data.status
            );
            this.$message.success("职位提交成功，等待审核");
            this.resetForm(formName);
            this.goBack();
          } else {
            this.$message.error(response.data.msg || "提交失败，请稍后重试");
          }
        } catch (error) {
          console.error("发布岗位失败：", error);
          this.$message.error("网络异常，提交失败");
        } finally {
          this.isSubmitting = false;
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped>
.publish-position-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.card-container {
  position: relative;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}
.close-btn {
  position: absolute; /* 绝对定位到右上角 */
  top: 15px;
  right: 15px;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
}

.publish-position-form {
  width: 100%;
  max-width: none;
  margin: 0;
}

.form-title {
  margin-bottom: 20px;
  color: #303133;
  font-size: 20px;
}

.salary-row {
  align-items: center;
}

.salary-divider {
  text-align: center;
  line-height: 38px;
  font-weight: bold;
}

.form-actions {
  margin-left: 120px;
  display: flex;
  gap: 10px;
}

.submit-button,
.reset-button {
  width: 120px;
}
</style>